<template>
  <div v-loading="loading">
    <div v-if="+relatedData.confuse_status === 3" class="empty-wrap text-left">
      <ul class="list-group">
        <li class="list-group-item">项目名称： {{ relatedData.customer_name }}</li>
        <li class="list-group-item">
          项目状态：
          <span class="text-danger">已拒绝</span>
        </li>
        <li class="list-group-item">拒绝时间： {{ relatedData.confuse_time }}</li>
        <li class="list-group-item">拒绝人：{{ relatedData.confuse_person }}</li>
        <li class="list-group-item">拒绝理由：{{ relatedData.confuse_des }}</li>
      </ul>
    </div>
    <div v-else>
      <table class="table table-bordered vertical-align-middle text-center">
        <colgroup>
          <col width="14%" />
          <col width="20%" />
          <col width="14%" />
          <col width="19%" />
          <col width="14%" />
          <col width="19%" />
        </colgroup>
        <tbody>
          <tr>
            <td>主体姓名</td>
            <td>{{ relatedData.customer_name || '' }}</td>
            <td>放款金额</td>
            <td :class="tdClass">
              <span v-if="isViewMode">{{ relatedData.reply_funds }} 万元</span>
              <el-input
                v-else
                placeholder="放款金额"
                clearable
                v-input-number="{ min: 0, fixed: 2 }"
                v-model="editData.reply_funds"
              >
                <span slot="append">万元</span>
              </el-input>
            </td>
            <td>贷款期限</td>
            <td :class="tdClass">
              <span v-if="isViewMode">{{ relatedData.months }} 月</span>
              <el-input
                v-else
                placeholder="贷款期限"
                clearable
                v-input-number="{ min: 0, fixed: 2 }"
                v-model="editData.months"
              >
                <span slot="append">月</span>
              </el-input>
            </td>
          </tr>
          <tr>
            <td>贷款利率(%)</td>
            <td :class="tdClass">
              <span v-if="isViewMode">
                {{ relatedData.load_rate || relatedData.load_rate || '-' }}%
              </span>
              <el-input
                v-else
                v-model="editData.load_rate"
                placeholder="贷款利率"
                v-input-number="{ fixed: 4 }"
              ></el-input>
            </td>
            <td>放款时间</td>
            <td :class="tdClass">
              <span class="px-2" v-if="isViewMode">
                {{ $utils.dateFormat(relatedData.load_date, 'yyyy年MM月dd日') }}
              </span>
              <el-date-picker
                v-else
                v-model="editData.load_date"
                :clearable="false"
                type="date"
                placeholder="放款开始时间"
                class="w-100"
                value-format="yyyy-MM-dd"
              ></el-date-picker>
            </td>
            <td>到期时间</td>
            <td :class="tdClass">
              <span class="px-2" v-if="isViewMode">
                {{ $utils.dateFormat(relatedData.load_end_date, 'yyyy年MM月dd日') }}
              </span>
              <el-date-picker
                v-else
                v-model="editData.load_end_date"
                :clearable="false"
                type="date"
                placeholder="放款结束时间"
                class="w-100"
                value-format="yyyy-MM-dd"
              ></el-date-picker>
            </td>
          </tr>

          <tr>
            <td>{{ attachTag }}</td>
            <td colspan="5" class="text-left">
              <div v-if="isViewMode">
                <div class="empty-wrap" v-if="!attachList.length">暂无附件（借据）</div>
                <attach-list v-else :attath-data="viewList" :show-label="false"></attach-list>
              </div>
              <upload-oss
                v-else
                multiple
                ref="attachUpload"
                :dir="dir"
                :file-list="attachList"
                :on-complete="handleAttachComplete"
              ></upload-oss>
            </td>
          </tr>
        </tbody>
      </table>

      <div class="text-center" v-if="!isViewMode">
        <el-button class="btn-long" type="primary" @click="onSave" :loading="submitLoading">
          登记
        </el-button>
        <el-button class="btn-long" type="danger" @click="handleReject" :loading="submitLoading">
          拒绝
        </el-button>
      </div>
    </div>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { enumRepayType } from '@/credit/plugins/enum'
import { attachAdapter } from '@/bank/components/attach/index'
import { deleteOss } from '@/common/api/oss'
import AttachList from '@/bank/views/business/limit/history/attach/AttachList'

export default {
  components: {
    AttachList,
  },
  props: {
    viewMode: { type: Boolean, default: true },
    queryId: String,
  },
  data() {
    return {
      loading: false,
      viewList: [],
      attachList: [],
      attachAready: [],
      parentTag: '放款附件',
      attachTag: '放款附件',
      params: {
        fields: [
          'months',
          'customer_name',
          'reply_funds',
          'load_end_date',
          'load_date',
          'load_rate',
          'loan_approval_status',
          'confuse_status',
          'confuse_time',
          'confuse_des',
          'bank_type',
          'bank_name',
          'bank_id',
        ],
      },
      tableName: 'customer_related',
      relatedData: {},
      // 还款计划
      enumRepayType,
      repayVisible: false,
      editData: {
        reply_funds: '',
        months: '',
        load_date: '',
        load_end_date: '',
        load_rate: '',
      },
      dir: 'credit/normal/register',
      submitLoading: false,
    }
  },
  computed: {
    ...mapGetters(['org', 'user']),
    isViewMode() {
      return this.viewMode
    },
    tdClass() {
      return this.isViewMode ? '' : 'input-td'
    },
  },
  watch: {
    queryId: {
      handler: function () {
        this.params['customer_related_id.eq'] = this.queryId
        this.getData()
        this.getAttach()
      },
      immediate: true,
    },
  },
  created() {},
  mounted() {},
  methods: {
    handleReject() {
      const data = {
        loan_approval_status: 4,
        confuse_status: 3,
        confuse_time: this.$utils.dateFormat(new Date()),
        confuse_person: this.user.realName,
      }
      this.$prompt('请输入拒绝说明', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputValidator: value => (!value ? '请输入拒绝说明' : true),
      }).then(({ value }) => {
        data.confuse_des = value
        this.$api
          .updateData(this.$serviceName, 'customer_related', this.queryId, data)
          .then(() => {
            this.$message.success('已拒绝！')
            this.$emit('success', true)
            this.beforeClose()
          })
          .catch(() => this.$message.error(`提交失败，请重试！`))
      })
    },
    handleAttachComplete(files) {
      this.submitLoading = true
      const { attachAready } = this
      const addFiles = files.filter(file => !attachAready.find(it => it.attachment === file.url))
      const deleteFiles = attachAready.filter(it => !files.find(file => file.url === it.attachment))

      const promise = []
      if (files.length) {
        promise.push(
          this.$api.addBatch(
            'credit',
            'datum_customer_attachment',
            addFiles.map(it => ({
              attachment: it.url,
              attachment_type: this.attachTag,
              parent_attachment_type: this.parentTag,
              customer_related_id: this.queryId,
              file_type: 2,
              remark: it.name,
            }))
          )
        )
      }
      if (deleteFiles.length) {
        promise.push(
          this.$api.deleteData({
            table: 'datum_customer_attachment',
            id: deleteFiles.map(it => it.id).join(','),
          }),
          deleteOss(deleteFiles.map(it => it.attachment))
        )
      }
      Promise.all(promise).then(() => {
        this.getAttach()
      })
      this.registerData()
    },
    getAttach() {
      if (!this.queryId) {
        return
      }
      this.$api
        .getData({
          table: 'datum_customer_attachment',
          params: {
            'customer_related_id.eq': this.queryId,
            'attachment_type.eq': this.attachTag,
          },
        })
        .then(res => {
          this.attachAready = res?.data ?? []
          this.initAttach()
        })
    },
    getData() {
      if (!this.queryId) {
        return
      }
      this.loading = true
      Promise.all([this.$api.getData(this.$serviceName, this.tableName, this.params)])
        .then(([res]) => {
          this.relatedData = res?.data?.[0] ?? {}
          this.initEdit()
        })
        .finally(() => {
          this.loading = false
        })
    },

    initAttach() {
      // 附件
      this.attachList = this.attachAready.map(attachAdapter)
      this.viewList = [
        {
          tag: this.attachTag,
          attachs: this.attachList,
        },
      ]
    },
    initEdit() {
      Object.keys(this.editData).forEach(key => {
        this.editData[key] = this.relatedData[key] || ''
      })
    },

    beforeClose() {
      this.$emit('update:visible', false)
    },
    onSave() {
      this.$utils
        .msgbox({
          message: `确定登记?`,
          type: 'info',
          beforeClose: () => this.$refs.attachUpload.submit(),
        })
        .catch(() => this.$message.error(`登记失败，请重试！`))
    },
    registerData() {
      const data = {
        ...this.editData,
        loan_approval_status: 3,
      }
      return this.$api
        .updateData(this.$serviceName, 'customer_related', this.queryId, data)
        .then(() => {
          this.$message.success('登记成功！')
          this.$emit('success', true)
          this.beforeClose()
        })
        .catch(err => {
          this.$message.error(err?.data?.error_description || '提交失败，请重试！')
        })
        .finally(() => {
          this.submitLoading = false
        })
    },
  },
}
</script>

<style lang="scss" scoped>
.vertical-align-middle td {
  vertical-align: middle;
}
.input-td /deep/ .el-input-group__append {
  background-color: #ffe;
  border: none;
}
.input-td {
  background-color: #ffffee;
}
</style>
